#!/bin/bash

# =============================================================================
# 修复权限并重新构建PKG
# =============================================================================

set -e

echo "🔧 修复应用权限并重新构建PKG..."

# 创建临时工作目录
TEMP_WORK="temp_app_fix"
rm -rf "$TEMP_WORK"
mkdir -p "$TEMP_WORK"

# 复制应用到临时目录
echo "📦 复制应用..."
cp -R build/bin/LimeReader.app "$TEMP_WORK/"

# 修复临时副本的权限
echo "🔨 修复权限..."
chmod +x "$TEMP_WORK/LimeReader.app/Contents/MacOS/LimeReader"
chown -R $(id -u):$(id -g) "$TEMP_WORK/LimeReader.app"
chmod -R 755 "$TEMP_WORK/LimeReader.app"

# 验证权限
echo "✅ 权限验证:"
ls -la "$TEMP_WORK/LimeReader.app/Contents/MacOS/"

# 创建PKG构建目录
echo "🏗️ 准备PKG构建..."
PKG_TEMP="pkg_temp_fixed"
ROOT_DIR="$PKG_TEMP/root"
SCRIPTS_DIR="$PKG_TEMP/scripts"

rm -rf "$PKG_TEMP"
mkdir -p "$ROOT_DIR/Applications"
mkdir -p "$SCRIPTS_DIR"

# 复制修复后的应用
cp -R "$TEMP_WORK/LimeReader.app" "$ROOT_DIR/Applications/"

# 创建安装脚本
cat > "$SCRIPTS_DIR/postinstall" << 'EOF'
#!/bin/bash
APP="/Applications/LimeReader.app"
if [ -d "$APP" ]; then
    chmod +x "$APP/Contents/MacOS/LimeReader"
    chown -R $USER:staff "$APP"
    echo "✅ 权限修复完成"
fi
EOF

chmod +x "$SCRIPTS_DIR/postinstall"

# 构建PKG
echo "📦 构建PKG..."
pkgbuild \
    --root "$ROOT_DIR" \
    --scripts "$SCRIPTS_DIR" \
    --identifier "com.limereader.app" \
    --version "2.7.2" \
    --install-location "/" \
    "LimeReader_v2.7.2_macOS_Fixed.pkg"

# 清理
rm -rf "$TEMP_WORK" "$PKG_TEMP"

if [ -f "LimeReader_v2.7.2_macOS_Fixed.pkg" ]; then
    echo "🎉 修复版PKG构建成功！"
    echo "📁 文件: LimeReader_v2.7.2_macOS_Fixed.pkg"

    size=$(stat -f%z "LimeReader_v2.7.2_macOS_Fixed.pkg" 2>/dev/null || echo "0")
    size_mb=$(echo "scale=2; $size / 1024 / 1024" | bc -l 2>/dev/null || echo "$(($size / 1024 / 1024))")
    echo "📊 大小: ${size_mb} MB"

    echo "✨ 这个版本应该能正确安装并运行！"
else
    echo "❌ 构建失败"
    exit 1
fi